package com.mxpio.erp.common.order.service.impl;

import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mxpio.erp.common.enums.NoticeStatusEnums.NoticeStatus;
import com.mxpio.erp.common.jpa.model.Notice;
import com.mxpio.erp.common.order.policy.NoticeContext;
import com.mxpio.erp.common.order.policy.NoticePolicy;
import com.mxpio.erp.common.order.provider.NoticeContextProvider;
import com.mxpio.erp.common.order.service.NoticeService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.system.service.impl.BaseServiceImpl;

/**
 * 通知单统一执行操作
 * @author mxpio
 *
 */
@Service
public class NoticeServiceImpl extends BaseServiceImpl<Notice> implements NoticeService {
	
	@Autowired(required = false)
	private List<NoticeContextProvider> noticeContextProviders;


	/**
	 * 通知单执行
	 */
	@Override
	@Transactional(readOnly = false)
	public NoticeContext execute(Notice notice, NoticePolicy policy) {
		
		// 通用NoticeContext初始化
		NoticeContext context = NoticeContext.init(notice);
		policy.config(context);
		// 遍历匹配的 Context提供器 补充Context信息
		if(CollectionUtils.isNotEmpty(noticeContextProviders)){
			for(NoticeContextProvider provider : noticeContextProviders){
				if(provider.supports(notice.getClass())){
					provider.provide(context);
				}
			}
		}
		// 执行通知单
		if(CollectionUtils.isEmpty(context.getErrors())){
			// 执行订单
			policy.apply(context);
		}
		return context;
	}


	@Override
	@Transactional(readOnly = false)
	public Result<? extends Notice> updateNoticeStatus(Notice notice, NoticeStatus noticeStatus) {
		notice.setNoticeStatus(noticeStatus.getStatusCode());
        this.update(notice);
        return Result.OK(notice);
	}
	
}
